<?php

namespace App\weapp\controller;

use App\model\CoinsLog;
use App\model\Post;
use App\model\School;
use App\model\Topic;
use App\model\User;
use App\model\UserViewPostLog;
use support\Request;

class PostController extends Controller
{
    //首页推荐
    public function homeList(Request $request)
    {
        $keyword = $request->input('keyword', ''); //搜索关键词
        $type = $request->input('type', 1); //1资讯  2推荐
        $sort = $request->input('sort', 2); //0最新回复(最近7天内 回复量最多) 1热度排序(评论+点赞)倒序 2最近发布(时间倒序)
        $userId = $request->loginUserId;
        $res = Post::select(['id', 'title', 'content', 'images', 'created_at', 'topic_id', 'school_id', 'user_id', 'top', 'share_count'])
            ->where('status', 1)
            ->with(['topic:id,title', 'school:id,name', 'user:id,username,avatarUrl'])
            ->withCount(['comments', 'views', 'zan'])
            ->when($userId, function ($query) use ($userId) {
                return $query->withCount(['zan as has_zan' => function ($q) use ($userId) {
                    $q->where('user_id', $userId);
                }]);
            }, function ($query) {
                $query->selectRaw('0 as has_zan');
            })
            ->when($type == 1, function ($query){
                return $query->whereNull('school_id')->orderBy('top');
            }, function ($query){
                return $query->whereNotNull('school_id');
            })
            ->when(!empty($keyword), function ($query) use($keyword) {
                return $query->where(function ($query) use($keyword){
                    $query->orWhere('title', 'like', "%$keyword%")->orWhere('content', 'like', "%$keyword%");
                });
            })
            ->when(!is_null($sort) && $type == 2, function ($query) use ($sort){
                switch ($sort){
                    case 0:
                        //最新回复(最近7天内 回复量最多)
                        return $query->withCount(['comments as dy7_comment_count' => function($q){
                            $q->where('created_at', '>',  date("Y-m-d H:i:s",strtotime("- 7 day")));
                        }])->orderByDesc('dy7_comment_count');
                    case 1:
                        //热度排序(评论+点赞)倒序
                        return $query->orderByRaw('(comments_count + zan_count) desc');
                    default:
                        return $query;
                }
            })
            ->orderByDesc('id')
            ->paginate($request->input('limit', 15));
        return success('首页推荐', $res, true);
    }

    //关注学校的帖子
    public function followList(Request $request)
    {
        $keyword = $request->input('keyword', ''); //搜索关键词
        $userId = $request->loginUserId;
        $res = Post::select(['posts.id', 'posts.title', 'posts.content', 'posts.images', 'posts.created_at', 'posts.topic_id',
            'posts.school_id', 'posts.user_id', 'share_count'])
            ->with(['topic:id,title', 'school:id,name', 'user:id,username,avatarUrl'])
            ->withCount(['comments', 'views', 'zan'])
            ->when($userId, function ($query) use($userId) {
                return $query->withCount(['zan as has_zan' => function ($q) use ($userId) {
                    $q->where('user_id', $userId);
                }]);
            }, function ($query) {
                $query->selectRaw('0 as has_zan');
            })
            ->leftJoin('user_follow_school', 'user_follow_school.school_id', '=', 'posts.school_id')
            ->where('user_follow_school.user_id', $request->loginUserId)
            ->when(!empty($keyword), function ($query) use($keyword) {
                return $query->where(function ($query) use($keyword){
                    $query->orWhere('title', 'like', "%$keyword%")->orWhere('content', 'like', "%$keyword%");
                });
            })
            ->where('status', 1)
            ->orderBy('top')
            ->orderByDesc('posts.id')
            ->paginate($request->input('limit', 15));
        return success('首页关注', $res, true);
    }

    //帖子详情
    public function detail(Request $request, $id)
    {
        $userId = $request->loginUserId;
        $res = Post::select(['id', 'title', 'content', 'images', 'created_at', 'topic_id', 'school_id', 'user_id', 'share_count'])
            ->with(['topic:id,title', 'school:id,name', 'user:id,username,avatarUrl', 'comments' => function ($query) use ($userId) {
                $query->select(['id', 'content', 'created_at', 'post_id', 'user_id', 'pid', 'reply_id', 'reply_user_id'])
                    ->where('status', 1)
                    ->orderBy('top')
                    ->orderByDesc('id')
                    ->with(['user', 'replyUser'])
                    ->withCount(['zan', 'comment', 'zan as has_zan' => function ($q) use ($userId) {
                        $q->where('user_id', $userId);
                    }]);
            }])
            ->withCount(['comments', 'views', 'zan', 'collect'])
            ->when($userId, function ($query) use($userId) {
                return $query->withCount(['zan as has_zan' => function ($q) use ($userId) {
                    $q->where('user_id', $userId);
                },'collect as has_collect' => function ($q) use ($userId) {
                        $q->where('user_id', $userId);
                    }]);
            }, function ($query) {
                $query->selectRaw('0 as has_zan, 0 as has_collect');
            })
            ->find($id);
        if (empty($res)) return error("帖子不存在");
        $res->is_self = $res->user_id == $userId;
        $commentList = $res->comments->where('reply_id', 0)->all();
        //是否禁言
        if($userId){
            $user_status = User::where('id', $userId)->value('status');
        }else{
            $user_status =1;
        }
        $res->user_status = $user_status;
        foreach ($commentList as $v) {
            $v->user_status = $user_status;
            $v->is_self = $v->user_id == $userId;
            $chilid = $res->comments->where('pid', $v->id);
            $v->comment_count = $chilid->count();
            $v->child = $chilid->values()->each(function ($item) use ($userId, $user_status) {
                $item->is_self = $item->user_id == $userId;
                $item->user_status = $user_status;
            });
        }
        unset($res->comments);
        $res->comment_list = $commentList;
        if ($userId) {
            //添加浏览记录
            UserViewPostLog::create([
                'user_id' => $userId,
                'post_id' => $id
            ]);
            $res->views_count += 1;
        }


        return success('帖子详情', $res);

    }

    //列表
    public function list(Request $request)
    {
        $topic_id = $request->input('topic_id', '');
        $keyword = $request->input('keyword', ''); //搜索关键词
        $school_id = $request->input('school_id', '');
        $sort = $request->input('sort', 2); //1最新回复 2最新帖子 3热门帖子 (浏览量)
        $userId = $request->loginUserId;
        $res = Post::select(['id', 'title', 'content', 'images', 'created_at', 'replay_at', 'topic_id', 'school_id', 'user_id', 'top', 'share_count'])
            ->with(['topic:id,title', 'school:id,name', 'user:id,username,avatarUrl'])
            ->withCount(['comments', 'views', 'zan'])
            ->when($userId, function ($query) use ($userId) {
                return $query->withCount(['zan as has_zan' => function ($q) use ($userId) {
                    $q->where('user_id', $userId);
                }]);
            }, function ($query) {
                $query->selectRaw('0 as has_zan');
            })
            ->when(!empty($topic_id), function ($query) use($topic_id) {
                return $query->where('topic_id', $topic_id);
            })
            ->when(!empty($school_id), function ($query) use ($school_id) {
                return $query->where('school_id', $school_id);
            })
            ->when(!empty($sort), function ($query) use ($sort){
                switch ($sort){
                    case 1:
                        return $query->orderByDesc('replay_at');
                    case 3:
                        return $query->orderByDesc('views_count');
                    case 2:
                    default:
                        return $query->orderByDesc('created_at');
                }
            })
            ->when(!empty($keyword), function ($query) use ($keyword) {
                return $query->where('title', 'like', "%$keyword%");
            })
            ->where('status', 1)
            ->orderBy('top')
            ->orderByDesc('id')
            ->paginate($request->input('limit', 15));
        return success('列表', $res, true);
    }


    //发帖所需学校信息
    public function postSchool(Request $request)
    {
        $user = User::with(['followSchools:id,name,pic', 'viewSchools:id,name,pic'])->find($request->loginUserId);
        return success('发帖学校', [
            'followSchools' => $user->followSchools,
            'viewSchools' => $user->viewSchools->take(20),
        ]);
    }

    //发帖学校搜索
    public function postSchoolSearch(Request $request)
    {
        $keyword = $request->input('keyword', '');
        if (empty($keyword)) return error("请输入搜索学校名称");
        //搜索话题
        return success('学校列表', School::select(['id', 'name', 'pic'])->where('name', 'like', "%$keyword%")->orderByDesc('id')->get());
    }

    //发帖所需话题信息
    public function postTopic(Request $request)
    {
        $user = User::find($request->loginUserId);
        return success('发帖话题', [
            'followTopics' => $user->followTopics,
            'viewTopics' => $user->viewTopics->take(20),
        ]);
    }

    //发帖话题搜索
    public function postTopicSearch(Request $request)
    {
        $keyword = $request->input('keyword', '');
        if (empty($keyword)) return error("请输入搜索话题名称");
        //搜索话题
        return success('话题列表', Topic::select(['id', 'title'])->where('title', 'like', "%$keyword%")->withCount('posts', 'comments', 'views')->orderByDesc('id')->get());
    }

    //发帖
    public function postSend(Request $request)
    {
        $data = $request->only(['school_id', 'title', 'content', 'images', 'topic_id']);
        $validator = validator($data, [
            'school_id' => 'required|integer',
            'title' => 'required|max:60',
            'content' => 'required',
            'images' => 'nullable|array|max:9',
            'topic_id' => 'nullable|integer'
        ], [
            'school_id.required' => '请选择学校版块',
            'title.required' => '请输入帖子标题',
            'title.max' => '帖子标题最大60字',
            'content.required' => '请输入帖子正文',
            'images.max' => '最大上传9张图片'
        ]);
        if ($validator->fails()) return error($validator->errors()->first());
        //文本安全内容检测
        $res = $this->wx()->content_security->checkText($data['title']);
        if($res['errmsg'] != "ok"){
            return error('发帖标题违规');
        }
        //内容
        $res = $this->wx()->content_security->checkText($data['content']);
        if($res['errmsg'] != "ok"){
            return error('发帖内容违规');
        }
        //图片
        foreach ($data['images'] as $img){
            $res = $this->wx()->content_security->checkImage($img);
            if($res['errmsg'] != "ok"){
                return error('发帖图片违规');
            }
        }
        $data['user_id'] = $request->loginUserId;
        try {
            Post::create($data);
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
        //发帖加积分
        CoinsLog::addCoinsByType($request->loginUserId, '发帖');
        return success('发帖成功');
    }
}
